package org.bitoy.shimmer.config;

import lombok.SneakyThrows;
import org.bitoy.shimmer.common.enums.DisplayableEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

@Component
public class EnumConverterFactory implements ConverterFactory<String, DisplayableEnum> {
    @Override
    public <T extends DisplayableEnum> Converter<String, T> getConverter(Class<T> targetType) {
        return new DisplayableEnumConverter<>(targetType);
    }

    private static class DisplayableEnumConverter<T extends DisplayableEnum> implements Converter<String, T> {
        private final Class<T> targetType;

        public DisplayableEnumConverter(Class<T> targetType) {
            this.targetType = targetType;
        }

        @SneakyThrows
        @Override
        public T convert(String source) {
            if (source.isEmpty()) return null;
            return DisplayableEnum.getEnum(this.targetType, source);
        }
    }
}
